package cn.school.educational.service.impl;

import cn.school.classManage.service.SchoolClassService;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.dao.HomeWorkInfoDao;
import cn.school.educational.dao.HomeworkCommentsDao;
import cn.school.educational.entity.HomeWorkInfo;
import cn.school.educational.entity.HomeworkComments;
import cn.school.educational.service.HomeWorkInfoService;
import cn.school.sys.entity.SysUserRole;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HomeWorkInfoServiceImpl extends ServiceImpl<HomeWorkInfoDao, HomeWorkInfo> implements HomeWorkInfoService {

    @Resource
    HomeworkCommentsDao homeworkCommentsDao;
    @Resource
    SchoolClassService schoolClassService;



    private String secretId;


    private String secretKey;


    private String regionStr;


    private String bucketName;

    @Override
    public IPage<HomeWorkInfo> pageList(HomeWorkInfo entiry) {
        LambdaQueryWrapper<HomeWorkInfo> wrapper = new LambdaQueryWrapper(entiry);
        List<SysUserRole> roleInfoList = SysUserUtils.getSysUser().getRoleInfoList();
        List<String> roleNames = roleInfoList.stream().map(SysUserRole::getRoleName).collect(Collectors.toList());

        if (!roleNames.contains("超级管理员")) {
            //根据登录的用户名去查询
            wrapper.eq(HomeWorkInfo::getCreateBy,SysUserUtils.getSysUser().getUsername());
        }
        IPage<HomeWorkInfo> page = page(new Page<>(entiry.getPageNum(), entiry.getPageSize()), wrapper);
        return page;
    }

    @Override
    public IPage<HomeWorkInfo> studentPageList(HomeWorkInfo entiry) {
        LambdaQueryWrapper<HomeWorkInfo> wrapper = new LambdaQueryWrapper(entiry);
        if(StringUtils.isEmpty(entiry.getClassId())){
            entiry.setCreateBy(SysUserUtils.getSysUser().getUsername().toString());
            wrapper.eq(HomeWorkInfo::getCreateBy,SysUserUtils.getSysUser().getUsername());
        }
        if(!StringUtils.isEmpty(entiry.getClassId())){
            wrapper.eq(HomeWorkInfo::getClassId,entiry.getClassId());
        }
        wrapper.orderByDesc(HomeWorkInfo::getCreateTime);
        IPage<HomeWorkInfo> page = page(new Page<>(entiry.getPageNum(), entiry.getPageSize()), wrapper);
        if(SysUserUtils.getSysUser().getUsername()==null){
            for (HomeWorkInfo record : page.getRecords()) {
                record.setCommentsList(findCommentsAll(record.getId()+""));
            }
        }else{
            for (HomeWorkInfo record : page.getRecords()) {
                record.setCommentsList(findCommentsDetails(record.getId()+""));
            }
        }

        return page;
    }

    @Override
    public int addOrUpdateHomeWork(HomeWorkInfo entity) {
        String username = SysUserUtils.getSysUser().getUsername();
        int num = 0;
        if(StringUtils.isEmpty(entity.getId())){
            entity.setCreateBy(username);
            entity.setCreateTime(new Date());
            num = this.baseMapper.insert(entity);
        }else{
            entity.setModifyBy(username);
            entity.setModifyTime(new Date());
            num = this.baseMapper.updateById(entity);
        }
        return num;
    }

    @Override
    public int deleteById(HomeWorkInfo entiry) {
        return this.baseMapper.deleteById(entiry.getId());
    }

    @Override
    public HomeWorkInfo workDetails(String id) {
        LambdaQueryWrapper<HomeWorkInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(HomeWorkInfo::getCreateBy,SysUserUtils.getSysUser().getUsername());
        wrapper.eq(HomeWorkInfo::getId,id);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public int addComments(HomeworkComments comments) {
        String name = SysUserUtils.getStudentUser().getName();
        String commentsName="";
        if(!StringUtils.isEmpty(name)){
            commentsName = name;
        }
        if(!StringUtils.isEmpty(SysUserUtils.getParentUser().getName())){
            commentsName = SysUserUtils.getParentUser().getName()+"-家长";
        }
        if(!StringUtils.isEmpty(SysUserUtils.getSysUser().getUsername())){
            commentsName = SysUserUtils.getSysUser().getUsername();
        }

        comments.setCreateBy(commentsName);
        comments.setCreateTime(new Date());
        comments.setCommentsUser(commentsName);
        comments.setPid("0");
        return homeworkCommentsDao.insert(comments);
    }

    @Override
    public List<HomeworkComments> findCommentsDetails(String workId) {
        LambdaQueryWrapper<HomeworkComments> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HomeworkComments::getHomeworkId,workId);
        wrapper.eq(HomeworkComments::getPid,"0");
        wrapper.orderByAsc(HomeworkComments::getCreateTime);
        List<HomeworkComments> list = homeworkCommentsDao.selectList(wrapper);
        return list;
    }

    private List<HomeworkComments> findCommentsAll(String workId) {
        List<HomeworkComments> list = homeworkCommentsDao.findHomeworkAllComments(workId);
        return list;
    }

    /**
     * 查询回复评论
     * @param pid
     * @return
     */
    @Override
    public List<HomeworkComments>  findreplyDetails(String pid) {
        List<HomeworkComments> list = homeworkCommentsDao.findreplyDetails(pid);
        getCommentsTree(list);
        log.info(JSON.toJSONString(list));
        return list;
    }




    private void getCommentsTree(List<HomeworkComments> list){

        for (HomeworkComments homeworkComments : list) {

            List<HomeworkComments> childList = homeworkCommentsDao.findreplyDetails(homeworkComments.getId()+"");
            homeworkComments.setChildren(childList);
            if(childList==null || childList.size()==0){
                continue;
            }else{
                getCommentsTree(childList);
            }
        }


    }

    @Override
    public int addReply(HomeworkComments comments) {
        String name = SysUserUtils.getStudentUser().getName();
        String commentsName="";
        if(!StringUtils.isEmpty(name)){
            commentsName = name;
        }
        if(!StringUtils.isEmpty(SysUserUtils.getParentUser().getName())){
            commentsName = SysUserUtils.getParentUser().getName()+"-家长";
        }
        if(!StringUtils.isEmpty(SysUserUtils.getSysUser().getUsername())){
            commentsName = SysUserUtils.getSysUser().getUsername();
        }
        comments.setCreateBy(commentsName);
        comments.setCreateTime(new Date());
        comments.setCommentsUser(commentsName);
        int num = homeworkCommentsDao.insert(comments);
        if(num>0){
            HomeworkComments commentsP =new HomeworkComments();
            commentsP.setId(Long.valueOf(comments.getPid()));
            commentsP.setIsReply("1");
            homeworkCommentsDao.updateById(commentsP);
        }

        return num;
    }

    /**
     * 作业文件上传
     * @param file
     * @return
     */
    @Override
    public String homeWorkFileUpload(MultipartFile file) throws IOException {
        COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
        Region region = new Region(regionStr);
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.http);
        COSClient cosClient = new COSClient(cred,clientConfig);
        //上传文件
        String key = UUID.randomUUID().toString() + file.getOriginalFilename();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getInputStream().available());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(),objectMetadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        String url="https://"+bucketName+".cos."+regionStr+".myqcloud.com/"+key;
        return url;
    }

    @Override
    @Transactional
    public Boolean deleteWithComments(String id) {
        LambdaQueryWrapper<HomeworkComments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HomeworkComments::getHomeworkId,id);
        List<HomeworkComments> homeworkComments = homeworkCommentsDao.selectList(queryWrapper);
        int result = this.baseMapper.deleteById(id);
        if(result > 0 && !homeworkComments.isEmpty()){
            homeworkCommentsDao.deleteBatchIds(
                    homeworkComments.stream()
                            .map(temp -> {
                                return (long) temp.getId();
                            }).collect(Collectors.toList())
            );
        }
        return true;
    }
}
